package service

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"go.mongodb.org/mongo-driver/mongo"
	"log"
	"net/http"
	"sensor/models"
	Util "sensor/util"
	"strconv"
	"strings"
)

var clientTmp *mongo.Client = nil
var username string = "admin"
var password string = "123456"
var url string = "mongodb://admin:123456@124.223.62.14:27017"

func stringToInt64(s string) int64 {
	t, _ := strconv.ParseInt(s, 10, 64)
	return t
}

func stringToFloat64(s string) float64 {
	t, _ := strconv.ParseFloat(s, 64)
	return t
}

func splitToFloat64Arr(s string) []float64 {
	s = s[1 : len(s)-1]
	arr := strings.Split(s, ",")
	data := make([]float64, 0)
	for _, t := range arr {
		data = append(data, stringToFloat64(t))
	}
	return data
}

func FilterData(c *gin.Context) {
	var form Util.GetDataForm
	if err := c.Bind(&form); err != nil {
		c.JSON(200, gin.H{
			"code":   -1,
			"msg":    "字段校验失败",
			"result": err.Error(),
		})
		return
	}

	startTime := stringToInt64(c.PostForm("startTime"))
	endTime := stringToInt64(c.PostForm("endTime"))
	deviceInfo := c.PostForm("deviceInfo")
	fallDown := c.PostForm("fallDown")
	limit := stringToInt64(c.PostForm("limit"))
	offset := stringToInt64(c.PostForm("offset"))

	data, err := models.FilterData(
		startTime,
		endTime,
		deviceInfo,
		fallDown,
		limit,
		offset,
	)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"msg":  err,
			"data": "",
			"code": 0,
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"msg":  "筛选数据成功",
		"data": data,
		"code": 1,
	})
}

func AddCollection(c *gin.Context) {
	var sd *models.SensorData
	sd = new(models.SensorData)
	sd.FallDown = c.PostForm("fallDown") == "true" || c.PostForm("fallDown") == "True"
	sd.Timestamp = stringToInt64(c.PostForm("timestamp"))
	sd.DeviceInfo = c.PostForm("deviceInfo")
	sd.SeqDataX = splitToFloat64Arr(c.PostForm("seqDataX"))
	sd.SeqDataY = splitToFloat64Arr(c.PostForm("seqDataY"))
	sd.SeqDataZ = splitToFloat64Arr(c.PostForm("seqDataZ"))

	err := models.InsertOneSensorData(sd)
	if err != nil {
		log.Println(err)
	}
	c.JSON(http.StatusOK, gin.H{
		"msg": "ok",
	})
}

func GetTotal(c *gin.Context) {
	sensor_data, err := models.GetSensorData()
	if err != nil {
		fmt.Println("出错了")
	}
	c.JSON(http.StatusOK, sensor_data)
}
